package top.zhdev.community.controller;

import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.zhdev.community.entity.Comment;
import top.zhdev.community.entity.DiscussPost;
import top.zhdev.community.entity.Page;
import top.zhdev.community.entity.User;
import top.zhdev.community.service.*;
import top.zhdev.community.utils.CommunityConstant;
import top.zhdev.community.utils.CommunityUtil;
import top.zhdev.community.utils.HostHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户信息处理器
 */
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    @Value("${qiniu.key.access}")
    private String access;

    @Value("${qiniu.key.secret}")
    private String secret;

    @Value("${qiniu.bucket.name}")
    private String bucketName;

    @Value("${qiniu.host}")
    private String hostUrl;

    private UserService userService;
    private LikeService likeService;
    private FollowService followService;
    private HostHolder hostHolder;
    private DiscussPostService discussPostService;
    private CommentService commentService;

    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    @Autowired
    public void setLikeService(LikeService likeService){
        this.likeService = likeService;
    }

    @Autowired
    public void setFollowService(FollowService followService){
        this.followService = followService;
    }

    @Autowired
    public void setHostHolder(HostHolder hostHolder){
        this.hostHolder = hostHolder;
    }

    @Autowired
    public void setDiscussPostService(DiscussPostService discussPostService){
        this.discussPostService = discussPostService;
    }

    @Autowired
    public void setCommentService(CommentService commentService){
        this.commentService = commentService;
    }

    /**
     * 个人主页
     * @param userId
     * @param model
     * @return
     */
    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId, Model model){
        User user = userService.getUserById(userId);
        if(user == null){
            throw new RuntimeException("该用户不存在");
        }

        //用户
        model.addAttribute("user",user);

        // 点赞数量
        int likeCount = likeService.getUserLikeCount(userId);
        model.addAttribute("likeCount",likeCount);

        // 关注数量
        long followeeCount = followService.getFolloweeCount(userId,ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);

        // 粉丝数量
        long followerCount = followService.getFollowerCount(userId,ENTITY_TYPE_USER);
        model.addAttribute("followerCount",followerCount);

        // 是否已关注
        boolean hasFollowed = false;
        if(hostHolder.getUser() != null){
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }

        model.addAttribute("hasFollowed",hasFollowed);
        return "/site/profile";
    }

    /**
     * 我的帖子
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @GetMapping("/mypost/{userId}")
    public String getMyPost(@PathVariable("userId") int userId, Page page,Model model){
        page.setLimit(5);
        page.setPath("/myposts/" + userId);
        int discussPostsCount = userService.getDiscussPostsByUserId(userId);
        page.setRows(discussPostsCount);
        User user = hostHolder.getUser();
        List<DiscussPost> posts = discussPostService.getDiscussPosts(userId, page.getOffset(),page.getLimit(),0);
        model.addAttribute("posts",posts);
        model.addAttribute("discussPostCounts",discussPostsCount);
        model.addAttribute("user",user);
        return "/site/my-post";
    }

    @GetMapping("/setting")
    public String getSettingPage(Model model){
        // 上传文件名称
        String fileName = CommunityUtil.generateUUID();
        // 设置相应信息
        StringMap policy = new StringMap();
        policy.put("returnBody",CommunityUtil.getJSONString(0));
        // 生成上传凭证
        Auth auth = Auth.create(access,secret);
        String uploadToken = auth.uploadToken(bucketName,fileName,3600,policy);
        model.addAttribute("uploadToken",uploadToken);
        model.addAttribute("fileName",fileName);
        return "site/setting";
    }

    @PostMapping("/header/url")
    @ResponseBody
    public String updateHeaderUrl(String fileName){
        if(StringUtils.isBlank(fileName)){
            return CommunityUtil.getJSONString(1,"文件名不能为空");
        }

        String url = hostUrl + fileName;
        userService.updateHeaderUrl(hostHolder.getUser().getId(),url);

        return CommunityUtil.getJSONString(0);
    }

    /**
     * 个人主页-我的回复
     */
    @GetMapping("/myreply/{userId}")
    public String getMyReply(@PathVariable("userId") int userId, Model model,Page page){
        User user = hostHolder.getUser();
        page.setRows(commentService.getCommentsRowsByUSerId(userId));
        page.setPath("/myreply/" + userId);
        List<Comment> comments = commentService.getCommentsByUserId(userId,page.getOffset(),page.getLimit());
        List<Map<String,Object>> list = new ArrayList<>();
        if(comments != null){
            for (Comment comment : comments){
                Map<String,Object> map = new HashMap<>();
                map.put("reply",comment);
                map.put("replyDiscussPostTitle",discussPostService.getDiscussPostById(comment.getEntityId()).getTitle());
                list.add(map);
            }
        }
        model.addAttribute("replys",list);
        model.addAttribute("user",user);
        model.addAttribute("replyCounts",page.getRows());
        return "/site/my-reply";
    }
}
